<?php

use Phinx\Migration\AbstractMigration;

class MigrateProductCategoryData extends AbstractMigration
{
    public function up()
    {
        // 检查旧表是否存在
        if ($this->hasTable('product_category')) {
            // 检查新表是否存在，如果不存在则创建
            if (!$this->hasTable('ky_product_category')) {
                $this->table('ky_product_category')
                    ->addColumn('name', 'string', ['limit' => 100, 'comment' => '分类名称'])
                    ->addColumn('parent_id', 'integer', ['default' => 0, 'comment' => '父级ID'])
                    ->addColumn('level', 'integer', ['default' => 1, 'comment' => '层级'])
                    ->addColumn('sort', 'integer', ['default' => 0, 'comment' => '排序'])
                    ->addColumn('status', 'boolean', ['default' => 1, 'comment' => '状态：0=禁用，1=启用'])
                    ->addColumn('icon', 'string', ['limit' => 100, 'null' => true, 'comment' => '图标'])
                    ->addColumn('description', 'string', ['limit' => 255, 'null' => true, 'comment' => '描述'])
                    ->addColumn('created_at', 'timestamp', ['null' => true])
                    ->addColumn('updated_at', 'timestamp', ['null' => true])
                    ->addIndex(['parent_id'])
                    ->addIndex(['level'])
                    ->addIndex(['status'])
                    ->create();
            }

            // 复制数据
            $rows = $this->fetchAll('SELECT * FROM product_category');
            foreach ($rows as $row) {
                $this->execute("INSERT INTO ky_product_category (
                    category_id, name, parent_id, level, sort, status, icon, description, created_at, updated_at
                ) VALUES (
                    {$row['category_id']},
                    '{$row['name']}',
                    {$row['parent_id']},
                    {$row['level']},
                    {$row['sort']},
                    {$row['status']},
                    " . ($row['icon'] ? "'{$row['icon']}'" : 'NULL') . ",
                    " . ($row['description'] ? "'{$row['description']}'" : 'NULL') . ",
                    " . ($row['created_at'] ? "'{$row['created_at']}'" : 'NULL') . ",
                    " . ($row['updated_at'] ? "'{$row['updated_at']}'" : 'NULL') . "
                )");
            }

            // 删除旧表
            $this->table('product_category')->drop()->save();
        }
    }

    public function down()
    {
        // 如果需要回滚，我们不做任何操作，因为这是数据迁移
    }
} 